﻿using System.Linq;
using System.Collections.Generic;

using Red.Core;

namespace Red.Controls.Depot.FileViewItemsProviders
{
    public class ChangelistItemsProvider : FileViewItemsProvider
    {
        #region Data

        private readonly int _changelistId;

        #endregion Data

        #region C-tor

        public ChangelistItemsProvider( int changelistId, string path, DepotInfo depot )
            : base( path, depot )
        {
            _changelistId = changelistId;
        }

        #endregion C-tor

        #region Public methods

        public override void EnumerateItems( IList<FolderInfo> folders, IList<FileInfo> files, IList<FileInfo> selectedFiles )
        {
            var changelistFiles = Depot.SourceControl.GetChangelistFiles( _changelistId );
            foreach ( var file in changelistFiles )
            {
                files.Add( new FileInfo
                {
                    FullPath = file.DepotPath.Path
                } );
            }
        }

        public override List<UpdateFileInfo> ProcessFilesBatch( IList<FileInfo> files, ref int index )
        {
            var result = new List<UpdateFileInfo>();

            IEnumerable<string> filePaths = files.Select( f => f.FullPath );
            var fileMetadata = Depot.SourceControl.GetFileMetaData( filePaths, _changelistId ).ToDictionary( item => item.DepotPath.Path.ToLower() );

            foreach ( FileInfo file in files )
            {
                Perforce.P4.FileMetaData p4Data = null;
                if ( fileMetadata.TryGetValue( file.FullPath.ToLower(), out p4Data ) ) // if didn't find file on the list, sth is broken, do not add
                {
                    string localPath = p4Data.LocalPath.Path;
                    result.Add( new UpdateFileInfo( index++, localPath, file, p4Data ) );
                }
            }

            return result;
        }

        #endregion Public methods
    }
}
